package com.lottery.server.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.alibaba.excel.EasyExcel;
import com.lottery.server.common.JsonResult;
import com.lottery.server.common.ResultCode;
import com.lottery.server.common.exception.BusinessException;
import com.lottery.server.entity.User;
import com.lottery.server.model.UserExcelVO;
import com.lottery.server.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/lottery/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public JsonResult<User> submit(@RequestBody User user) {
        // 检查手机号是否已参与抽奖
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        if (userService.count(queryWrapper) > 0) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "该手机号参加活活动,已完成信息填报,请更换手机重试");
        }

        validateUser(user);
        userService.save(user);
        return JsonResult.success(user);
    }

    @GetMapping("/list")
    public JsonResult<Page<User>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String productCategory) {

        Page<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), User::getName, name)
                .or()
                .like(StringUtils.hasText(name), User::getCompanyName, name);
        wrapper.like(StringUtils.hasText(phone), User::getPhone, phone);
        wrapper.like(StringUtils.hasText(productCategory), User::getProductCategory, productCategory);
        wrapper.orderByDesc(User::getCreateTime);
        return JsonResult.success(userService.page(page, wrapper));
    }

    @GetMapping("/{id}")
    public JsonResult<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }
        return JsonResult.success(user);
    }

    @PutMapping
    public JsonResult<User> update(@RequestBody User user) {
        if (user.getId() == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "用户ID不能为空");
        }
        validateUser(user);
        if (!userService.updateById(user)) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }
        return JsonResult.success(user);
    }

    @DeleteMapping("/{id}")
    public JsonResult<Void> delete(@PathVariable Long id) {
        if (!userService.removeById(id)) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }
        return JsonResult.success(null);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 获取所有用户数据
        List<User> users = userService.list();

        // 转换为Excel VO对象
        List<UserExcelVO> excelData = new ArrayList<>();
        for (User user : users) {
            UserExcelVO vo = new UserExcelVO();
            vo.setName(user.getName());
            vo.setCompanyName(user.getCompanyName());
            vo.setPosition(user.getPosition());
            vo.setPhone(user.getPhone());
            vo.setEmail(user.getEmail());
            vo.setProductCategory(user.getProductCategory());
            vo.setCreateTime(user.getCreateTime() != null ? user.getCreateTime().toString() : "");
            vo.setId(user.getId());
            excelData.add(vo);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户列表", StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 导出Excel
        EasyExcel.write(response.getOutputStream(), UserExcelVO.class)
                .sheet("用户列表")
                .doWrite(excelData);
    }

    private void validateUser(User user) {
        if (!StringUtils.hasText(user.getName())) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "用户姓名不能为空");
        }
        if (!StringUtils.hasText(user.getCompanyName())) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "公司名称不能为空");
        }
        if (!StringUtils.hasText(user.getPosition())) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "职位不能为空");
        }
        if (!StringUtils.hasText(user.getPhone())) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "手机号不能为空");
        }
        if (!StringUtils.hasText(user.getProductCategory())) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "感兴趣的产品类别不能为空");
        }
    }
} 